HTTPException
fastapi内置的异常模块,可以自定义响应头
items = {"foo": "The Foo Wrestlers"}
@app.get("/items-header/{item_id}")
async def read_item_header(item_id: str):
if item_id not in items:
raise HTTPException(
status_code=404,
detail="Item not found",
headers={"X-Error": "There goes my error"},
)
return {"item": items[item_id]}
自定义异常类
自己抛自己接
exception_handler可以接受全局我们抛出的指定异常类
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
class UnicornException(Exception):
def __init__(self, name: str):
self.name = name
app = FastAPI()
@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
return JSONResponse(
status_code=418,
content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
)
@app.get("/unicorns/{name}")
async def read_unicorn(name: str):
if name == "yolo":
raise UnicornException(name=name)
return {"unicorn_name": name}
重写内置异常捕获
参数校验不通过的时候,fastapi会默认报422的错,且错误格式固定,如果想修改这种错误格式,就可以通过全局异常捕获参数校验类来重写
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
# body是放在响应体重,exc.body是源数据
content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}),
)
class User(BaseModel):
id: Optional[int] = Field(...,gt=110)
username: str = Field(...,max_length=3,min_length=2)
sex: Optional[str] = None
login_time: Optional[int] = None
class Config:
orm_mode = True
@app.post("/items}")
async def read_item(item_id: User):
return {"a": item_id}
FastAPI与Starlette的HTTPException
FastAPI HTTPException
继承自 Starlette’s HTTPException
。
唯一的区别是,FastAPI HTTPException
允许你在response添加头信息。主要在内部用于OAuth 2.0以及一些安全相关的功能。
因此,通常我们在代码中抛出FastAPI HTTPException
异常。
但是,当我们注册异常处理器的时候,我们应该注册为Starlette HTTPException
。
这样,当Starlette的内部代码或者Starlette扩展插件抛出Starlette HTTPException
时,我们的处理器才能正常捕获和处理这个异常。
如果我们要在代码中同时使用这两个类,为了避免命名冲突,我们可以重命名其中一个类。
from fastapi import HTTPException
from starlette.exceptions import HTTPException as StarletteHTTPException
点我就给你看点有意思的
- 本文链接:http://huang_zhao.gitee.io/task/2021/07/02/python/%E6%A1%86%E6%9E%B6/fast-api/fastapi%E9%94%99%E8%AF%AF%E5%A4%84%E7%90%86/
- 版权声明:本博客所有文章除特别声明外,均默认采用 许可协议。